/*
 * @(#) ProbableToActualDaoImpl.java
 * Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproducuce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */
package in.ac.dei.edrp.cms.daoimpl.studentregistration;


import in.ac.dei.edrp.cms.common.utility.MyException;
import in.ac.dei.edrp.cms.dao.studentregistration.ProbableToActualDao;
import in.ac.dei.edrp.cms.domain.activitymaster.ActivityMaster;
import in.ac.dei.edrp.cms.domain.activitymaster.CountProcessRecorList;
import in.ac.dei.edrp.cms.domain.studentregistration.StudentInfoGetter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * Implementation class of ProbableToActualDao
 * @author Manpreet Kaur
 * @date 01-03-2011
 * @version 1.0
 */
public class ProbableToActualDaoImpl 
    implements ProbableToActualDao {
    private static Logger logObj = Logger.getLogger(ProbableToActualDaoImpl.class);
    TransactionTemplate transactionTemplate = null;
	protected SqlMapClient sqlMapClient = null;
	
	int totalRecords=0;
	int correctProcessed=0;
	int rejectedProcessed=0;
	int inError=0;
	
    public void setSqlMapClient(SqlMapClient sqlMapClient) {
        this.sqlMapClient = sqlMapClient;
    }
	
    /**
     * default constructor
     */
    public ProbableToActualDaoImpl(){
    	
    }

    /**
     * Method for setting TransactionTemplate bean
     * @param transactionTemplate
     */
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    
    public ProbableToActualDaoImpl(SqlMapClient sqlMapClient,
			TransactionTemplate transactionTemplate) {
		super();
		this.sqlMapClient = sqlMapClient;
		this.transactionTemplate = transactionTemplate;
	}
    
    
    
 
    /**
     * Method for transferring students probable program details to
     * to-program details if student fails in semester he/she registered previously.
     * @param programObject
     * @return String  
     */
    @SuppressWarnings("unchecked")
	public CountProcessRecorList transferOfProbables(final StudentInfoGetter programObject) {
    	
    	final CountProcessRecorList resultList=new CountProcessRecorList();
    	
    	
    	 transactionTemplate.execute(new TransactionCallback() {
             Object savepoint = null;

             public List<CountProcessRecorList> doInTransaction(TransactionStatus status) {
    	List studentList=new ArrayList<StudentInfoGetter>();
    	List<StudentInfoGetter> detailsList=null;
    	
        try {
        	
        	StudentInfoGetter newSemesterGroup=(StudentInfoGetter) sqlMapClient.queryForObject("pta.getSemesterGroup",programObject);
        	
        
             studentList = sqlMapClient.queryForList("pta.getStudentList",
                    programObject);
             
             totalRecords=studentList.size();
             
            if(studentList.size()>0){
            	
            	Iterator<StudentInfoGetter> iterator=studentList.iterator();
            	while(iterator.hasNext()){
            		
            		StudentInfoGetter studentObj= iterator.next();
            		
            		// getting old semester group                    
                    StudentInfoGetter oldProgramObject=programObject;
                    oldProgramObject.setSemesterCode(studentObj.getOldSemesterCode());
                	StudentInfoGetter oldSemesterGroup=(StudentInfoGetter) sqlMapClient.queryForObject("pta.getSemesterGroup",programObject);
            		
                	
                	// if student's group is being changed
                	if(!(newSemesterGroup.getSemesterGroup().equalsIgnoreCase(oldSemesterGroup.getSemesterGroup()))){
            		
                		studentObj.setModifierId(programObject.getModifierId());
                		detailsList = sqlMapClient.queryForList("pta.getStatus",studentObj);
            		
            		if(detailsList.size()>0){
            			try{
            				 //creating savepoint
            	            savepoint = status.createSavepoint();
            	            
            		if(!(detailsList.get(0).getStatus().equalsIgnoreCase("PAS"))){
            			sqlMapClient.update("pta.updateTempStdProg",studentObj);
            			sqlMapClient.update("pta.updateTempStdMaster",studentObj);
            			sqlMapClient.update("pta.updateTempStdCourse",studentObj);
            			sqlMapClient.update("pta.updateStaging",studentObj);
            			sqlMapClient.getDataSource().getConnection()
                        .commit();
            			correctProcessed++;
            		}
            			}catch (Exception e) {
            				inError++;
            				 status.rollbackToSavepoint(savepoint);
						}
            		
            		}
            	}
            	}           	
            	
            }
//            else{            	
//           // signifies that no student exists for given entries.
//            	 throw new MyException("N");
//            	
//            }
        } catch (Exception e) {
        	logObj.error(e);                                         
           
          //signifies failure
            throw new MyException(e.getMessage());
        }
        
       new CountProcessRecorList(totalRecords, correctProcessed, rejectedProcessed, inError,true);
        
        System.out.println("returning from inside");
        //signifies success
		return null;
             }
         });
         System.out.println("returning from outside");

    	//signifies success
		return null;
    }
    
    
    
    
    
    
    
    
    
    
    
    

	/*
	 * Method added  to check pass fail 
	 */
	

	/**
	 * Method for checking whether student is pass or fail in semester
	 * @param rollNumber
	 * @param semesterList
	 * @param inputObj
	 * @param maxFailSubjects
	 * @return
	 */
	public String checkStudentPassFail(List<String> semesterList,ActivityMaster inputObj,
			int maxFailSubjects){
		// inputObj must contain program,branch,specialization,semester, 
		//semester_start_date,semester_end_date and roll number for student
		
		// bean class will be changed and accordingly parameters in query
		
		// semesterList will contain current semester, and other semesters having 
		//same group as current semester and sequence less than current semester
		
		/*
		 * Code to be removed
		 */
//		semesterList.add("SM1");
//		semesterList.add("SM2");
//		inputObj.setProgramId("0001001");
//		inputObj.setBranchId("XXX");
//		inputObj.setSpecializationId("XXX");		
//		inputObj.setSemesterStartDate("2011-01-01");
//		inputObj.setSemesterEndDate("2011-05-31");
//		inputObj.setRollNumber("r1");
//		maxFailSubjects=1;
		
		try{
		int totalRemedial=0;
		
		for(int i=0;i<semesterList.size();i++){		
			//change semester code on each iteration
			inputObj.setSemesterCode(semesterList.get(i));
			
			ActivityMaster totalRem=(ActivityMaster) sqlMapClient.queryForObject("common.countStudentRemedials", inputObj);
			String count=totalRem.getSize();
			totalRemedial=totalRemedial+Integer.parseInt(count);			
		}
		System.out.println(totalRemedial);
		if(totalRemedial==0){
			return "PAS";
		}else if(totalRemedial>maxFailSubjects){
			return "FAL";	
		}else if(totalRemedial<=maxFailSubjects){
			return "REM";	
		}
		}catch (Exception e) {
			logObj.error(e);
		}
		return null;	
	
	}
	
    
    
    
    
    
    
    
    
    
    
}





